import { defineConfig, loadEnv } from 'vite'
import * as path from 'path'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// Element-Plus 按需导入插件
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

const pathSrc = path.resolve(__dirname, 'src')

const config = loadEnv('', './')
const target = config?.VITE_PROXY_URL ?? 'http://test.com' // 默认测试环境

// https://vitejs.dev/config/
export default defineConfig({
  //src目录的配置
  resolve: {
    // alias: [{ find: '@', replacement: path.resolve(__dirname, './src') }]
    alias: {
      '@': pathSrc
    }
  },
  plugins: [
    vue(),
    vueJsx(),
    /**
     *  自动导入 Element Plus 相关函数，如：ElMessage, ElMessageBox... (带样式)
     */
    AutoImport({
      resolvers: [
        // 自动导入 Element Plus 组件
        ElementPlusResolver()
      ],
      dts: path.resolve(pathSrc, 'auto-imports.d.ts')
    }),
    /**
     *  自动注册 Element Plus 相关组件
     */
    Components({
      resolvers: [
        // 自动注册 Element Plus 组件
        ElementPlusResolver()
      ],
      dts: path.resolve(pathSrc, 'components.d.ts')
    })
  ],
  server: {
    port: 3080,
    proxy: {
      // 使用json-server作为服务器
      '^/api': {
        target: 'http://localhost:3000/',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
        // configure: (proxy, options) => {
        //   // proxy 是 'http-proxy' 的实例
        // }
      }
      // '/api': {
      //   target,
      //   changeOrigin: true
      // }
    }
  },
  build: {
    commonjsOptions: {
      ignoreTryCatch: false
    }
    // outDir: '../resources/static'
  },
  css: {
    modules: {
      scopeBehaviour: 'local',
      generateScopedName: (name) => {
        return name
      }
    }
  }
})
